<template>
  <view class="user-box">
    <view class="user-box-baj" :style="'background-image: url(' + backgroundImage + ');'">
      <view class="box-top-const">
        <!-- 未登录显示登录按钮 -->
        <button
          v-if="!isLogin"
          class="box-top-const-tox"
          open-type="getPhoneNumber"
          @getphonenumber="onGetPhoneNumber"
        ></button>

        <!-- 登录后显示头像，无点击事件 -->
		<view class="" style="width: 120rpx;"  v-else>
			<image
			  class="box-top-const-tox disabled"
			  :src="avatarImage"
			  mode="aspectFill"
			  style="border-radius:50%; z-index: 1;"
			/>
		</view>
       

        <view class="box-top-const-text">{{ userName }}</view>
		
		
		 <view class="box-top-const-text">{{dianhua}}</view>
      </view>
    </view>
	
    <view
      class="user-cosnt"
      v-for="(item, index) in listcoent"
      :key="index"
	  v-if="item.show"
      @click="handleItemClick(item)"
    >
      <view class="user-cosnt-xinxi">
        <image
          :src="item.image"
          style="width: 48upx; height: 48upx; margin-right: 20upx;"
          mode="widthFix"
        ></image>
        <text>{{ item.name }}</text>
      </view>
      
    </view>

    <!-- 登录状态显示退出登录按钮，阻止冒泡 -->
    <view v-if="isLogin" class="login" @click.stop="logout">退出登录</view>
  </view>
</template>

<script>
import api from '../../api/Channel.js'
import request from '../../api/index.js'
import suffixAddress from '../../api/suffixAddress.js'
export default {
  data() {
    return {
      backgroundImage: '',
      avatarImage: null,
      userName: '登陆',
      isLogin: false,
	  dianhua:'',
      listcoent: [
        { image: '../../static/images/user/个人信息.svg', name: '个人信息', id: 8,show:true },
        // { image: '../../static/images/user/商家入驻.svg', name: '档口管理', id: 0 },
        { image: '../../static/images/user/上传二维码.svg', name: '二维码', id: 1 ,show:true},
        { image: '../../static/images/user/上传.svg', name: '上传', id: 2 ,show:false},  
		{ image: '../../static/images/user/上传.svg', name: '批量上传', id: 11 ,show:false},
		{ image: '../../static/images/user/上传.svg', name: '机器上传', id: 16 ,show:false},
		
		{ image: '../../static/images/user/上传.svg', name: '样品册上传', id: 13 ,show:false},
		{ image: '../../static/images/user/上传.svg', name: '批量修改', id: 15 ,show:false},
		
		
		{ image: '../../static/images/user/上传.svg', name: 'AI实验室', id: 10 ,show:false},
		{ image: '../../static/images/user/上传.svg', name: 'AI训练素材', id: 12 ,show:false},
		{ image: '../../static/images/user/上传.svg', name: 'AI生成历史', id: 9 ,show:false},
        // { image: '../../static/images/user/KHCFDC_管理.svg', name: '管理模式', id: 5 },
        // { image: '../../static/images/user/下架.svg', name: '下架列表', id: 3 },
        // { image: '../../static/images/user/删除.svg', name: '删除列表', id: 4 },
        // { image: '../../static/images/user/批量处理／批量修改-copy.svg', name: '单个修改', id: 6 },
        // { image: '../../static/images/user/icon_推广.svg', name: '我的推广', id: 7 },
      ],
    }
  },

  onLoad() {
    this.checkLogin()
    this.loadDefaultAvatar()
	this.convertImageToBase64()
  },
  onShow (e){
		this.checkLogin()
		this.loadDefaultAvatar()
	
  },
  methods: {
	convertImageToBase64(){
		let th = this
		uni.getFileSystemManager().readFile({
			filePath: '/static/images/user/我的.png',
			encoding: 'base64',
		    success: res => {
			   th.backgroundImage = 'data:image/jpeg;base64,' + res.data;
			},
			fail: err => {
			  console.error('readFile 失败', err);
			}
		  });
	},
	async info(){
		let obj = {
			url: api.Channel + suffixAddress.add().info
		}
		let res = await request(obj)
		this.avatarImage = res.data.avatar.url
	},
    async checkLogin() {
      const token = uni.getStorageSync('token')
      if (token) {
        this.isLogin = true
        try {
			console.log(token)
			let obj = {
					url: api.Channel + suffixAddress.add().info,
				    method: 'GET',
			}
		 let resa = await request(obj)
         const result = resa || {}
		 wx.setStorageSync('user', result); // 存
		 this.avatarImage = result.data.avatar.url
		 this.userName = result.data.name
		 this.dianhua =  result.data.cellphone
		 console.log(result.data.cellphone)
		 
		 if(result.data.config.enableAiGenerate){
			 this.listcoent.forEach(el=>{
			 	  if(el.id == 12 || el.id == 9 || el.id == 10){
			 		  el.show = true
			 	  }
			 })
		 }else{
			 this.listcoent.forEach(el=>{
			 	  if(el.id == 12 || el.id == 9 || el.id == 10){
			 		  el.show = false
			 	  }
			 })
		 }
		  if(result.data.config.enableUploadCommodity){
			  this.listcoent.forEach(el=>{
				  if(el.id == 2 || el.id == 11 || el.id == 13 || el.id == 15 || el.id == 16){
					  el.show = true
				  }
			  })
		  }else{
			this.listcoent.forEach(el=>{
			  if(el.id == 2 || el.id == 11 || el.id == 13 || el.id == 15 || el.id == 16){
				  el.show = false
			  }
			})
		  }
		 // if(result.data.config.enableAliImageSearch){
			//   this.listcoent[2].show = true
		 // }else{
			//  this.listcoent[2].show = false
		 // }
		 console.log()
		
          
        } catch (error) {
          console.error('获取用户信息失败', error)
          this.logout()
        }
      } else {
        this.isLogin = false
        this.userName = '登陆'
        this.loadDefaultAvatar()
      }
    },

    logout() {
		this.listcoent[2].show = false
      try {
        uni.removeStorageSync('token')
      } catch (err) {
        console.warn('清除 token 失败', err)
      }
      this.isLogin = false
      this.userName = '登陆'
      this.loadDefaultAvatar()
	  this.dianhua = ''
	  wx.removeStorageSync('user');
	  this.listcoent.forEach(el=>{
	  	  if(el.id == 12 || el.id == 9 || el.id == 10 || el.id == 2 || el.id == 11 || el.id == 13){
	  		  el.show = false
	  	  }
	  })
      uni.showToast({
        title: '退出登录成功',
        icon: 'success',
        duration: 1500,
      })
    },

   async onGetPhoneNumber(e) {
     if (e.detail.errMsg !== 'getPhoneNumber:ok') {
       uni.showToast({ title: '授权失败', icon: 'none' })
       return
     }
     try {
       // 关键：只有拿到非空的 code 才 resolve，否则直接 reject
       const { code } = await new Promise((resolve, reject) => {
         uni.login({
           success: res => {
             if (res && res.code) {
               resolve(res)    // 拿到 code，继续往下跑
             } else {
               reject(new Error('未获取到 code'))
             }
           },
           fail: err => reject(err)
         })
       })
   
       // 走到这里就能保证有 code
       const { encryptedData, iv } = e.detail
       const obj = {
         url: api.Channel + suffixAddress.add().usingWx,
         method: 'POST',
         header: { 'content-type': 'application/json' },
         data: { code, encryptedData, iv }
       }
   
       const res = await request(obj)
       const result = res || {}
       if (result.code === 0 && result.data.token) {
         uni.setStorageSync('token',result.data.token)
         uni.showToast({ title: '登录成功', icon: 'success' })
         await this.checkLogin()
       } else {
         throw new Error(result.errorMessage || '登录失败')
       }
   
     } catch (err) {
       uni.showToast({ title: '登录异常', icon: 'none' })
       console.error('登录失败', err)
     }
   },


    loadDefaultAvatar() {
      this.avatarImage = '/static/images/user/我的.png'
    },

    handleItemClick(item) {
      if (!this.isLogin) {
        uni.showToast({
          title: '请先登录',
          icon: 'none',
        })
        return
      }

      switch (item.id) {
		case 9:
		  uni.navigateTo({ url: '/pages/aiGeneratedHistory/aiGeneratedHistory' })
		  break
        case 8:
          uni.navigateTo({ url: '/pages/mation/mation' })
          break
        case 0:
          uni.navigateTo({ url: '/pages/dangkogli/dangkogli' })
          break
        case 1:
          uni.navigateTo({ url: '/pages/erweima/erweima' })
          break
        case 2:
          uni.navigateTo({ url: '/pages/shangc/shangc' })
          break
        case 7:
          uni.navigateTo({ url: '/pages/shangcfenx/shangcfenx' })
          break
        case 3:
        case 4:
          uni.navigateTo({ url: '/pages/selecttype/selecttype' })
          break
		  case 10:
		    uni.navigateTo({ url: '/pages/aishengc/aishengc' })
		break
		  case 11:
		  uni.navigateTo({ url: '/pages/pilSshangc/pilSshangc' })
		break
		case 12:
		  uni.navigateTo({ url: '/pages/aiXunlian/aiXunlian'})
		break
		case 13:
		  uni.navigateTo({ url: '/pages/SamplebookletUpload/SamplebookletUpload' })
		break
		case 15:
		  uni.navigateTo({ url: '/pages/BatchUpload/BatchUpload' })
		break
		case 16:
		  uni.navigateTo({ url: '/pages/JiqiShangchuan/JiqiShangchuan' })
		break
        default:
          break
      } 
    },
  },
}
</script>

<style>
page{
	background:#f9f9f9;
	min-height: 100vh;
}
.user-box {
  background-color: #f9f9f9;
  padding-bottom: 20upx;
}

.user-box-baj {
  width: 100vw;
  height: 300rpx;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  position: relative;
}

.box-top-const {
  position: relative;
  z-index: 1;
  width: 100vw;
  height: 180rpx;
  display: flex;
  align-items: center;
  padding-left: 40rpx;
  padding-top: 120rpx;
}

.box-top-const-tox {
  width: 110rpx !important;
  height: 110rpx !important;
  background-color: #ffffff;
  border-radius: 50%;
  margin: 0 !important;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}

.box-top-const-tox.disabled {
  cursor: default;
  pointer-events: none;
  filter: grayscale(70%);
  opacity: 0.7;
}

.box-top-const-text {
  color: #fff;
  margin-left: 25rpx;
  font-size: 42rpx;
  font-weight: 600;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6);
  max-width: 60vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-cosnt {
  display: flex;
  justify-content: space-between;
  padding: 30upx 30upx;
  background-color: #fff;
  height: 110rpx;
  margin: 15upx 25upx 10upx 25upx;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.07);
  box-sizing: border-box;
  border-radius: 12rpx;
  font-size: 34upx;
  align-items: center;
  transition: background-color 0.3s ease;
  cursor: pointer;
}

.user-cosnt:hover {
  background-color: #f0f0f0;
}

.login {
  margin: 40rpx auto;
  width: 60%;
  text-align: center;
  background-color: #ff4d4f;
  color: #fff;
  padding: 20rpx 0;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  cursor: pointer;
}
</style>
